<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $uses = array('User');
	
	function beforeFilter() {		
		parent::beforeFilter();
	}
	
	function admin_index() {		
		$this->User->recursive = 2;
		$this->set('users',$this->paginate());
	}

        function admin_add() {
            if(!empty($this->data)) {
                if($this->User->save_user($this->data)) {
                    $this->Session->setFlash(__('USER_SAVED_OK',true));
                    $this->redirect(array('action' => 'index'),null,true);
                } else {
                    $this->Session->setFlash(__('USER_SAVED_ERROR',true));
                }
            }
            $groups = $this->User->Group->find('list');
            $this->set(compact('groups'));
        }
	
        function admin_change_password($id) {
            if(!empty($this->data)) {
                if($this->User->save_user($this->data)) {
                    $this->redirect_to(__('Password changed successfully',true),$this);
                } else {
                    $this->Session->setFlash(__('Password could not be saved. Try again!',true));
                }
            } else {
              $this->data = $this->User->read(null,$id);
            }
        }

	function admin_edit($id = null) {
		if (!$this->User->findById($id)) {
			$this->redirect_to(__('USERS_INVALID',true),$this);
		}
		if(!empty($this->data)) {
                    if($this->User->save($this->data['User'])) {
                            $this->redirect_to(__('USER_SAVED_OK',true),$this);
                    } else {
                            $this->Session->setFlash(__('USER_SAVED_ERROR',true));
                    }
		} else {
			$this->data = $this->User->read(null,$id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}
	
	function admin_delete($id = null) {
		if(!$this->User->findById($id)) {
			$message = __('USER_INVALID',true);
		}
		if ($this->User->del($id)) {
			$message = __('USER_DELETED_OK',true);
		}
		$this->redirect_to($message,$this);
	}
	
	function admin_login() {
		$this->layout = 'login';
	}
	
	function admin_logout() {
		$this->redirect($this->Auth->logout(),null,true);
	}

	function admin_delete_users() {
		if($this->User->deleteAll(array('User.id'=>$this->data['UsersDelete']))) {
			$message = __('USERS_DELETED_OK',true);
		} else {
			$message = __('USERS_DELETED_ERROR',true);
		}
		$this->redirect_to($message,$this);
	}
}
?>